package com.price.custom

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.widget.AppCompatEditText

class IconEditText @JvmOverloads constructor(
    context: Context,
    attributeSet: AttributeSet? = null
): AppCompatEditText(context, attributeSet) {
    companion object {
        const val LEFT = 0
        const val RIGHT = 1
    }

    private var clickListener: OnIconClickListener? = null

    // SAM 接口
    fun interface OnIconClickListener {
        fun onIconClick(direction: Int, editText: IconEditText)
    }

    fun setOnIconClickListener(l: OnIconClickListener) {
        clickListener = l
    }

    // 这里只是仅仅处理点击事件了，如果考虑更复杂的UI效果需要另外添加逻辑
    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        if (event.action == MotionEvent.ACTION_UP) {
            val rightDrawable = compoundDrawables[2]
            val leftDrawable = compoundDrawables[0]
            leftDrawable?.let {
                val rect = Rect(
                    0,//paddingStart
                    paddingTop,
                    paddingStart + it.intrinsicWidth + compoundDrawablePadding,
                    paddingBottom + it.bounds.bottom
                )
                if (rect.contains(event.x.toInt(), event.y.toInt())) {
                    clickListener?.onIconClick(LEFT, this)
                }
            }
            rightDrawable?.let {
                val rect = Rect(
                    measuredWidth - 2*paddingEnd - it.bounds.width(),
                    0,
                    measuredWidth,// - paddingEnd
                    measuredHeight
                )
                if (rect.contains(event.x.toInt(), event.y.toInt())) {
                    clickListener?.onIconClick(RIGHT, this)
                    return true
                }
            }
        }
        return super.onTouchEvent(event)
    }
}
